package com.atguigu.juc.future;

import lombok.val;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @Description: FutureTask + 线程池 提高效率
 * @author： yeswater
 * @create： 2024/5/28
 */

public class FutureThreadPoolDemo {
	
	public static void main(String[] args) {
		//m1();
		m2();
	}
	
	/**
	 * cost time  ==> 40ms
	 */
	private static void m2() {
		ExecutorService threadPool = Executors.newFixedThreadPool(3);
		
		long start = System.currentTimeMillis();
		
		FutureTask<String> futureTask1 = new FutureTask<>(() -> {
			try {
				TimeUnit.MILLISECONDS.sleep(500);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
			return "task1 over";
		});
		threadPool.submit(futureTask1);
		
		FutureTask<String> futureTask2 = new FutureTask<>(() -> {
			try {
				TimeUnit.MILLISECONDS.sleep(300);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
			return "task2 over";
		});
		threadPool.submit(futureTask2);
		
		FutureTask<String> futureTask3 = new FutureTask<>(() -> {
			try {
				TimeUnit.MILLISECONDS.sleep(200);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
			return "task3 over";
		});
		threadPool.submit(futureTask3);
		
		long end = System.currentTimeMillis();
		System.out.println("cost time  ==> " + (end - start) + "ms");
	}
	
	/**
	 * cost time  ==> 1001ms
	 * thread name ==> main
	 */
	private static void m1() {
		long start = System.currentTimeMillis();
		try {
			TimeUnit.MILLISECONDS.sleep(500);
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
		try {
			TimeUnit.MILLISECONDS.sleep(300);
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
		try {
			TimeUnit.MILLISECONDS.sleep(200);
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
		
		long end = System.currentTimeMillis();
		System.out.println("cost time  ==> " + (end - start) + "ms");
		System.out.println("thread name ==> " + Thread.currentThread().getName());
	}
	
}
